package controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Gebruiker;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import database.WriteDAO;

/**
 * Servlet implementation class NewAuction
 */
public class NewAuction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public NewAuction() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String foto = "";
		String titel = "";
		Double prijs = 0.00;
		Gebruiker verkoper = (Gebruiker) request.getSession().getAttribute("gebruiker");
		String omschrijving = "";
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		// check if the http request is a multipart request
		// with other words check that the http request can have uploaded files
		if (isMultipart) {

			//  Create a factory for disk-based file items
			FileItemFactory factory = new DiskFileItemFactory();
			//  Create a new file upload handler
			ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
			// Set upload parameters
			// See Apache Commons FileUpload for more information
			// http://jakarta.apache.org/commons/fileupload/using.html
			servletFileUpload.setSizeMax(-1);

			try {

				String directory = "";

				// Parse the request
				List<?> items = servletFileUpload.parseRequest(request);

				// Process the uploaded items
				Iterator<?> iter = items.iterator();

				while (iter.hasNext()) {
					FileItem item = (FileItem) iter.next();

					// the param tag directory is sent as a request parameter to
					// the server
					// check if the upload directory is available
					if (item.isFormField()) {

						String name = item.getFieldName();

						if (name.equalsIgnoreCase("directory")) {

							directory = item.getString();
						}
						if(name.equals("naam")){
							titel = item.getString();
						}
						if(name.equals("prijs")){
							prijs = Double.parseDouble(item.getString().replaceAll(",", "."));
						}
						if(name.equals("beschrijving")){
							omschrijving = item.getString();
						}

						// retrieve the files
					} else {

						// the fileNames are urlencoded
						String fileName = URLDecoder.decode(item.getName(), "UTF-8");
						File file = new File("");
						if(!fileName.equals("")){
							file = new File(directory, verkoper.getId() + System.currentTimeMillis() + fileName);
							file = new File(getServletContext().getRealPath("/images/"), file.getPath());
						}




						//default plaatje voor als niets word geupload. 

						if(file.getName().equals("")){
							foto = "./images/default.jpg";
						} else {
							foto = "./images/"+file.getName();
						}

						// retrieve the parent file for creating the directories
						File parentFile = file.getParentFile();

						if (parentFile != null) {
							parentFile.mkdirs();
						}

						// writes the file to the filesystem
						if(!foto.contains("default")){
							item.write(file);
						}

					}
				}

			} catch(NumberFormatException nfe){
				request.setAttribute("error", "nonumbernewauction");
				RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
				view.forward(request, response);
				return;
			}
			catch (Exception e) {
				e.printStackTrace();
				response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			}

			response.setStatus(HttpServletResponse.SC_OK);

		} else {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
		if(titel.equals("") || omschrijving.equals("")){
			request.setAttribute("error", "emptyfieldsnewauction");
			RequestDispatcher view = request.getRequestDispatcher("/WEB-INF/errorpages/error.jsp");
			view.forward(request, response);
			return;
		}else{
			WriteDAO write = new WriteDAO();
			write.addVeiling(titel, foto, prijs, verkoper, omschrijving);

			response.sendRedirect("./VeilingController");
		}
	}

}
